import { v4 as uuidv4 } from 'uuid'

export default {
  data () {
    return {
      // 默认地址，可在使用 mixin 的组件里覆盖
      webSocketUrl: 'ws://dev.beiktech.com:7000'
    }
  },
  methods: {
    openWebSocket () {
      const token = this.$store.state.user.token
      this.wsInstance = new WebSocket(`${this.webSocketUrl}/websocket/message/${uuidv4()}/${token}`)
      this.wsInstance.onopen = (event) => {
        // onWebSocketOpen: 实现该方法来监听 WebSocket 打开事件
        this.onWebSocketOpen && this.onWebSocketOpen(event)
      }
      this.wsInstance.onmessage = (event) => {
        // onWebSocketMessage: 实现该方法来处理 WebSocket 返回的消息
        this.onWebSocketMessage && this.onWebSocketMessage(event)
      }
      this.wsInstance.onclose = (event) => {
        // onWebSocketClose: 实现该方法来监听 WebSocket 关闭事件
        this.onWebSocketClose && this.onWebSocketClose(event)
      }
    },
    closeWebSocket () {
      if (this.wsInstance) {
        this.wsInstance.close()
        this.wsInstance = null
      }
    },
    // 发送消息到 WebSocket 后台
    sendMessageByWebSocket (message) {
      if (this.wsInstance) {
        this.wsInstance.send(message)
      } else {
        console.log('未连接到 WebSocket 服务器')
      }
    }
  },
  beforeDestroy () {
    this.closeWebSocket()
  }
}
